import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, DatePicker, Select, Space, Tag, Modal, message, Descriptions, Popconfirm, InputNumber, Image } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined, EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';
import ActivityForm from './ActivityForm';

const { RangePicker } = DatePicker;
const { Option } = Select;

// 获取团购活动列表
const fetchActivities = async (params) => {
  return request('/api/v1/groupbuy/activity', {
    method: 'GET',
    params,
  });
};

// 获取团购活动详情
const fetchActivityDetail = async (id) => {
  return request(`/api/v1/groupbuy/activity/${id}`, {
    method: 'GET',
  });
};

// 创建团购活动
const createActivity = async (data) => {
  return request('/api/v1/groupbuy/activity', {
    method: 'POST',
    data,
  });
};

// 更新团购活动
const updateActivity = async (data) => {
  const { id, ...rest } = data;
  return request(`/api/v1/groupbuy/activity/${id}`, {
    method: 'PUT',
    data: rest,  // 不要在请求体中包含id
  });
};

// 删除团购活动
const deleteActivity = async (id) => {
  return request(`/api/v1/groupbuy/activity/${id}`, {
    method: 'DELETE',
  });
};

// 上传图片
const uploadImage = async (file) => {
  const formData = new FormData();
  formData.append('file', file);
  return request('/api/v1/upload', {
    method: 'POST',
    data: formData,
  });
};

const GroupbuyActivity = () => {
  const [activities, setActivities] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [activityForm] = Form.useForm(); // Keep this for the modal form
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [currentActivity, setCurrentActivity] = useState(null);
  const [formTitle, setFormTitle] = useState('创建团购活动');

  // 获取团购活动列表
  const fetchActivityList = async () => {
    try {
      setLoading(true);
      const res = await fetchActivities({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setActivities(res.data.list || []);
      } else {
        message.error(res.message || '获取团购活动列表失败');
      }
    } catch (error) {
      console.error('获取团购活动列表出错:', error);
      message.error('获取团购活动列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchActivityList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 查看活动详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchActivityDetail(record.id);
      if (res.success) {
        setCurrentActivity(res.data);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取活动详情失败');
      }
    } catch (error) {
      console.error('获取活动详情出错:', error);
      message.error('获取活动详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理添加活动
  const handleAdd = () => {
    setFormTitle('创建团购活动');
    setCurrentActivity(null);
    setFormVisible(true);
  };

  // 处理编辑活动
  const handleEdit = async (record) => {
    setFormTitle('编辑团购活动');
    setLoading(true);
    try {
      // 获取最新的门店和场地信息，并将名称转换为ID
      const storeRes = await request('/api/v1/store', { method: 'GET' });
      if (!storeRes.success) {
        message.error('获取门店列表失败');
        return;
      }
      const stores = storeRes.data.list;

      const storeIds = record.applicable_stores
        ? record.applicable_stores
            .map((name) => stores.find((s) => s.name === name)?.id)
            .filter(Boolean)
        : [];

      let venues = [];
      if (storeIds.length > 0) {
        const requests = storeIds.map((storeId) =>
          request(`/api/v1/venue?store_id=${storeId}`, { method: 'GET' })
        );
        const responses = await Promise.all(requests);
        venues = responses.reduce((acc, res) => {
          if (res.success && res.data.list) {
            return acc.concat(res.data.list);
          }
          return acc;
        }, []);
      }

      const venueIds = record.applicable_venues
        ? record.applicable_venues
            .map((name) => venues.find((v) => v.name === name)?.id)
            .filter(Boolean)
        : [];
      console.log("storeIds:",storeIds, " venueIds:",venueIds)
      setCurrentActivity({
        ...record,
        applicable_stores: storeIds,
        applicable_venues: venueIds,
      });

      setFormVisible(true);
    } catch (error) {
      message.error('加载编辑数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理删除活动
  const handleDelete = async (id) => {
    try {
      setLoading(true);
      const res = await deleteActivity(id);
      if (res.success) {
        message.success('删除团购活动成功');
        fetchActivityList();
      } else {
        message.error(res.message || '删除团购活动失败');
      }
    } catch (error) {
      console.error('删除团购活动出错:', error);
      message.error('删除团购活动失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理表单提交
  const handleFormSubmit = async (values) => {
    try {
      const data = {
        ...values,
        support_balance: values.support_balance || false,
      };

      // 仅在值为数字时进行转换
      if (typeof values.original_price === 'number') {
        data.original_price = Math.round(values.original_price * 100);
      }
      if (typeof values.group_price === 'number') {
        data.group_price = Math.round(values.group_price * 100);
      }

      setLoading(true);
      let res;
      if (currentActivity) {
        res = await updateActivity({
          id: currentActivity.id,
          ...data,
        });
      } else {
        res = await createActivity(data);
      }

      if (res.success) {
        message.success(currentActivity ? '更新成功' : '创建成功');
        setFormVisible(false);
        fetchActivityList();
      } else {
        message.error(res.message || (currentActivity ? '更新失败' : '创建失败'));
      }
    } catch (error) {
      console.error('表单提交错误:', error);
      message.error('表单验证失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '活动名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
    },
    {
      title: '原价',
      dataIndex: 'original_price',
      key: 'original_price',
      width: 100,
      render: (price) => `¥${(price / 100).toFixed(2)}`,
    },
    {
      title: '可抵扣时长',
      dataIndex: 'deductible_hours',
      key: 'deductible_hours',
      width: 120,
      render: (hours) => `${hours}小时`,
    },
    {
      title: '团购价',
      dataIndex: 'group_price',
      key: 'group_price',
      width: 100,
      render: (price) => `¥${(price / 100).toFixed(2)}`,
    },
    {
      title: '成团人数',
      dataIndex: 'min_members',
      key: 'min_members',
      width: 100,
      render: (min, record) => `${min}${record.max_members ? `-${record.max_members}` : ''}人`,
    },
    {
      title: '每人限购',
      dataIndex: 'limit_per_member',
      key: 'limit_per_member',
      width: 100,
      render: (limit) => limit > 0 ? `${limit}件` : '不限',
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      key: 'start_time',
      width: 180,
      render: (time) => moment(time * 1000).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      key: 'end_time',
      width: 180,
      render: (time) => moment(time * 1000).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '支持余额支付',
      dataIndex: 'support_balance',
      key: 'support_balance',
      width: 120,
      render: (support_balance) => (
        <Tag color={support_balance ? 'green' : 'red'}>
          {support_balance ? '是' : '否'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此团购活动吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              icon={<DeleteOutlined />} 
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.name) {
      params.name = values.name;
    }
    if (values.status) {
      params.status = values.status;
    }
    if (values.dateRange && values.dateRange.length === 2) {
      params.startTime = values.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
      params.endTime = values.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
    }
    
    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1, // 重置到第一页
    });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };

  return (
    <PageContainer>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            创建团购活动
          </Button>
        </div>
        
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="name" label="活动名称">
            <Input placeholder="请输入活动名称" allowClear />
          </Form.Item>
          <Form.Item name="status" label="活动状态">
            <Select placeholder="请选择活动状态" style={{ width: 150 }} allowClear>
              <Option value="active">进行中</Option>
              <Option value="inactive">已禁用</Option>
              <Option value="pending">未开始</Option>
              <Option value="ended">已结束</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="活动时间">
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={activities}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1300 }}
        />

        {/* 活动详情弹窗 */}
        <Modal
          title="团购活动详情"
          visible={detailVisible}
          onCancel={() => setDetailVisible(false)}
          footer={[
            <Button key="close" onClick={() => setDetailVisible(false)}>
              关闭
            </Button>,
          ]}
          width={800}
        >
          {currentActivity && (
            <>
              <Descriptions bordered column={2}>
                <Descriptions.Item label="活动名称">{currentActivity.name}</Descriptions.Item>
                <Descriptions.Item label="原价">¥{(currentActivity.original_price / 100).toFixed(2)}</Descriptions.Item>
                <Descriptions.Item label="团购价">¥{(currentActivity.group_price / 100).toFixed(2)}</Descriptions.Item>
                <Descriptions.Item label="成团人数">
                  {currentActivity.min_members}
                  {currentActivity.max_members ? `-${currentActivity.max_members}` : ''}人
                </Descriptions.Item>
                <Descriptions.Item label="每人限购">
                  {currentActivity.limit_per_member > 0 ? `${currentActivity.limit_per_member}件` : '不限'}
                </Descriptions.Item>
                <Descriptions.Item label="已售数量">{currentActivity.sold_count || 0}件</Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Tag color={currentActivity.status === 1 ? 'green' : 'red'}>
                    {currentActivity.status === 1 ? '启用' : '禁用'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="开始时间">
                  {moment(currentActivity.start_time * 1000).format('YYYY-MM-DD HH:mm:ss')}
                </Descriptions.Item>
                <Descriptions.Item label="结束时间">
                  {moment(currentActivity.end_time * 1000).format('YYYY-MM-DD HH:mm:ss')}
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {moment(currentActivity.created_at * 1000).format('YYYY-MM-DD HH:mm:ss')}
                </Descriptions.Item>
                <Descriptions.Item label="更新时间">
                  {moment(currentActivity.updated_at * 1000).format('YYYY-MM-DD HH:mm:ss')}
                </Descriptions.Item>
                <Descriptions.Item label="活动描述" span={2}>
                  {currentActivity.description || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="可抵扣时长" span={2}>
                  {currentActivity.deductible_hours}小时
                </Descriptions.Item>
                <Descriptions.Item label="可用门店" span={2}>
                  {currentActivity.applicable_stores?.length > 0 ? currentActivity.applicable_stores.join('、') : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="可用场地" span={2}>
                  {currentActivity.applicable_venues?.length > 0 ? currentActivity.applicable_venues.join('、') : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="支持余额支付">
                  <Tag color={currentActivity.support_balance ? 'green' : 'red'}>
                    {currentActivity.support_balance ? '是' : '否'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="可用星期" span={2}>
                  {currentActivity.available_weekdays?.length > 0 ? currentActivity.available_weekdays.map(w => `周${['日', '一', '二', '三', '四', '五', '六'][w]}`).join('、') : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="可用时段" span={2}>
                  {currentActivity.available_times?.length > 0 ? currentActivity.available_times.map(t => `${t.start_time}-${t.end_time}`).join('、') : '-'}
                </Descriptions.Item>

              </Descriptions>
              {currentActivity.image && (
                <div style={{ marginTop: 16, textAlign: 'center' }}>
                  <p>活动图片：</p>
                  <Image
                    width={400}
                    src={currentActivity.image}
                    alt="活动图片"
                  />
                </div>
              )}
            </>
          )}
        </Modal>

        {/* 创建/编辑活动弹窗 */}
        <Modal
          title={formTitle}
          visible={formVisible}
          onCancel={() => setFormVisible(false)}
          footer={null} // 使用ActivityForm自己的页脚
          width={800}
          destroyOnClose
        >
          <ActivityForm
            form={activityForm}
            initialValues={currentActivity ? {
              ...currentActivity,
              original_price: currentActivity.original_price / 100,
              group_price: currentActivity.group_price / 100,
            } : {}}
            onFinish={handleFormSubmit}
            onCancel={() => setFormVisible(false)}
            loading={loading}
          />
        </Modal>
      </Card>
    </PageContainer>
  );
};

export default GroupbuyActivity;